package open.tech.dawn.web.core.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import open.tech.dawn.core.error.ServiceException;
import open.tech.dawn.web.core.entity.Code;
import open.tech.dawn.web.core.error.NoPermissionException;
import open.tech.dawn.web.core.error.TokenExpiredException;
import open.tech.dawn.web.core.support.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class ExceptionController {


    @ExceptionHandler(TokenExpiredException.class)
    public Object tokenExpiredException(HttpServletRequest request, Throwable ex) {
        Result result = Result.createError("token失效");
        result.setCode(Code.token_expired);
        return result;
    }

    @ExceptionHandler(NoPermissionException.class)
    public Object noPermissionException(HttpServletRequest request, Throwable ex) {
        Result result = Result.createError("无权访问");
        result.setCode(Code.not_auth);
        return result;
    }


    // 捕捉所有业务异常
    @ExceptionHandler(ServiceException.class)
    public Object globalException(HttpServletRequest request, Throwable ex) {
        log.error("业务异常", ex);
        Throwable rootCause = ExceptionUtil.getRootCause(ex);
        if (rootCause == null) {
            rootCause = ex;
        }
        return Result.createError(rootCause.getMessage());
    }


}
